package pl.szpadel.android.gadu;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ViewFlipper;

public class ChatActivity extends Activity {

	private static final String TAG = "ChatActivity";
	
	/// Activity state tracking
	private boolean mStarted = false;
	private boolean mResumed = false;
	
	/// Main control - view flipper
	private ViewFlipper mChatFlipper = null;
	
	/// Mapping - remote user id to view
	private HashMap<Long, View> mViewsByUid = new HashMap<Long, View>();
	
	// Extras recognised by the activity
	public static final String EXTRA_SENDER = "sender";
	
	public ChatActivity() {
		super();
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // app initialisation (in case this is the first activity created)
        App.createInstance(getApplicationContext());
        App.getInstance().setChatActivity(this);
        
        startService(new Intent(this, CommunicationService.class));
        
        // init ui
        setContentView(R.layout.chat_window);

        mChatFlipper = (ViewFlipper)findViewById(R.id.ChatFlipper);
        AGLog.i(TAG, "activity created");
    }
    
    @Override
    public void onStart() {
    	super.onStart();
    	AGLog.i(TAG, "Activity started");
    	
    	createChats();
    	
    	mStarted = true;
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
        AGLog.i(TAG, "activity resumed");
        
        Intent intent = getIntent();
        if (intent.hasExtra(EXTRA_SENDER)) {
        	long sender = intent.getLongExtra(EXTRA_SENDER, 0);
        	AGLog.i(TAG, "resumend with sender: " + sender);
        	
        	// make sure that chat for the user exists
        	App.getInstance().getChatManager().getOrCreateChat(sender);
        	
        	// try to bring specific activity to view
    		showChat(sender);
        }
        
        mResumed = true;
    }
    
    @Override
    protected void onPause() {
    	super.onResume();
        AGLog.i(TAG, "activity paused");
        mResumed = false;
    }
    
    @Override
    public void onStop() {
    	super.onStop();
    	AGLog.i(TAG, "Activity stopped");
    	mStarted = false;
    }

    @Override
    public void onDestroy() {
    	super.onDestroy();
        App.getInstance().setChatActivity(null);
        AGLog.i(TAG, "activity destroyed");
    }
    
    @Override
    protected void onNewIntent (Intent intent) {
    	long sender = 0;
        if (intent.hasExtra(EXTRA_SENDER)) {
        	sender = intent.getLongExtra(EXTRA_SENDER, 0);
        }
    	
    	AGLog.i(TAG, "new intent, sender=" + sender);
    	setIntent(intent);
    }

    /// Called when new chat is created
    public void onChatCreated(ChatManager.Chat chat) {
    	AGLog.d(TAG, "onChatCreated for " + chat.getRemoteUser());
    	
    	if (mStarted) {
    		long uid = chat.getRemoteUser();
    		if (! mViewsByUid.containsKey(uid)) {
    			AGLog.i(TAG, "Adding chat with : " + uid);
    			
    			addView(chat);
    		} else {
    			AGLog.w(TAG, "Created chat that already exists");
    		}
    	}
    }
    
    /// Called when new message is received.
    /// Should return true if the message will be displayed immediately and no further notification is required
    public boolean onNewMessage(ChatManager.Message msg) {
    	AGLog.d(TAG, "onNewMessage for " + msg.sender);
    	
    	if (mResumed) {
    		assert(mChatFlipper != null);
    		
    		long uin = msg.sender;
    		int idx = mChatFlipper.getDisplayedChild();
    		View chatView = mChatFlipper.getChildAt(idx);
    		if (mViewsByUid.containsKey(uin)) {
    			if (chatView == mViewsByUid.get(uin)) {
    				AGLog.i(TAG, "onNewMessage: supressing notidfication, chat already open");
    				return true;
    			}
    		}
    		else {
    			AGLog.w(TAG, "message received for chat that does not exists");
    		}
    	}
    	
    	return false;
    }
    
    
    /////////////////////////////////////////////////////
    // Implementation
    
	private void createChats(){
		Map<Long, ChatManager.Chat> chats = App.getInstance().getChatManager().getChats();
		AGLog.i(TAG, "createChats()");
		
		// clear current chat views
		mChatFlipper.removeAllViews();
		mViewsByUid.clear();
		
		// create views
		for (Map.Entry<Long, ChatManager.Chat> entry : chats.entrySet()) {	
			long uid = entry.getKey();
			ChatManager.Chat chat = entry.getValue();
			AGLog.i(TAG, "createChats: creating view for " + uid);
			
			addView(chat);
		}
	}
	
	/// Creates and adds view for chat
	/// returns newly created view
	private View addView(ChatManager.Chat chat) {
		View chatView = createChatView(chat);
		mViewsByUid.put(chat.getRemoteUser(), chatView);
		mChatFlipper.addView(chatView);
		
		return chatView;
	}
	
	//// Creates view associated with specific chat
	private View createChatView(ChatManager.Chat chat) {
		
		// inflate view
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.chat_view, null);
		ListView list = (ListView)view.findViewById(R.id.ChatList);
		final EditText edit = (EditText)view.findViewById(R.id.ChatText);
		Button button = (Button)view.findViewById(R.id.ChatButton);
		final long uin = chat.getRemoteUser();
		
		// button listener
		button.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				onSendButtonPressed(uin, edit);
			}
		});
		
		// editor enter listener
		edit.setOnKeyListener(new View.OnKeyListener() {
		    public boolean onKey(View v, int keyCode, KeyEvent event) {
		        // If the event is a key-down event on the "enter" button
		        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
		            (keyCode == KeyEvent.KEYCODE_ENTER)) {
		          // Perform action on key press
		        	onSendButtonPressed(uin, edit);
		          return true;
		        }
		        return false;
		    }
		});
		
		list.setAdapter(new ChatListAdapter(chat));
		
		return view;
	}

	/// Shows chat for with user
	private void showChat(long uin) {
		AGLog.d(TAG, "trying to show chat for " + uin);
		
		// setup title
		String name = App.getInstance().getContactInfoManager().uinToName(uin);
		setTitle(getText(R.string.title_chat_with) + " " + name);
		
		// notify chat manager that chat is displayed
		App.getInstance().getChatManager().chatDisplayed(uin);
		
		// show proper page
    	if (mViewsByUid.containsKey(uin)) {
    		View v = mViewsByUid.get(uin);
    		int idx = mChatFlipper.indexOfChild(v);
    		if (idx < 0) {
    			AGLog.w(TAG, "View does not belong to the fillper!!! uin=" + uin);
    		} else {
    			mChatFlipper.setDisplayedChild(idx);
    		}
    	} else {
    		AGLog.e(TAG, "no view for the sender " + uin);
    	}
	}
	
	/// button press handle
	private void onSendButtonPressed(long uin, EditText textView) {
		String text = textView.getText().toString();
		
		AGLog.d(TAG, "Send button clicked, uin="+uin+", text="+text);
		
		App.getInstance().getChatManager().sendMessage(uin, text);
		
		textView.setText("");
	}
	
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.chat_activity_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        // -- contact list --
        case R.id.menu_contact_list: {
        	Intent intent = new Intent(this, ContactListActivity.class);
        	startActivity(intent);
        	return true;
        }
        // -- show info --
        case R.id.menu_show_contact_info: {
    		int idx = mChatFlipper.getDisplayedChild();
    		View chatView = mChatFlipper.getChildAt(idx);
    		// sequential search in view set, bleeh
    		long uin = 0;
    		for( Entry<Long, View> entry : mViewsByUid.entrySet()) {
    			if (entry.getValue() == chatView ) {
    				uin = entry.getKey();
    				break;
    			}
    		}
    		if (uin > 0 ) {
    			Intent intent = new Intent(this, ContactInfoActivity.class);
    			intent.putExtra(ContactInfoActivity.EXTRA_UIN, uin);
    			startActivity(intent);
    		}
        	return true;
        }
        // -- settings --
        case R.id.menu_config:
        	startActivity(new Intent(this, SettingsActivity.class));
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }
	
}
